/**
 * Created by Administrator on 2017/12/2.
 */
define(function(require, exports, module) {
    var $=require('zepto');
        md=require('md5');//加签文
    module.exports = {
        setCookie:function(name, value, days){
            if(days){
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }else{
                var expires = "";
            }
            document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
        },
        getCookie:function(name){
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for(var i = 0; i < ca.length; i++){
                var c = ca[i];
                while(c.charAt(0) == ' '){c = c.substring(1, c.length);}
                if(c.indexOf(nameEQ) == 0){return decodeURIComponent(c.substring(nameEQ.length, c.length));}
            }
            return null;
        },
        deleteCookie:function(name){
            this.setCookie(name, "", -1);
        },
        setItem:function(key,value){
            if(window.localStorage){
                localStorage.setItem(key,value);
            }else{
                this.setCookie(key,value,3650);
            }
        },
        getItem:function(key){
            return  window.localStorage?localStorage.getItem(key):this.getCookie(key);
        },
        removerAdver:function () {
            var _this=this;
            var preg = new Array();//定义正则表达式数组
            preg[0] = /^(http|ws){1}[s]*:[\/]{2}([a-zA-Z\d]*[\.]{1})*abc[\.]{1}com[\/]{1}/;//网站根域名，如abc.com
            preg[1] = /^http[s]*:[\/]{2}([a-zA-Z\d]*[\.]{1})*qq[\.]{1}com[\/]{1}/;//链接腾讯的一些资源
            preg[2] = /^http[s]*:[\/]{2}([a-zA-Z\d]*[\.]{1})*anquan[\.]{1}org[\/]{1}/;//链接安全联盟资源
            preg[3] = /^weixin(ping)?:[\/]{2}[a-zA-Z\d]+/;//防止微信公众号里的一些资源被屏蔽，以免影响分享之类的操作
            var preg_length = preg.length;
            var ishttps = 'https:' == document.location.protocol ? true : false;
            //如果您的网站既有http又有https协议的页面，那么在https下就不必继续过滤了
            if (ishttps == false) {
                var stop = setTimeout(function () {
                    var scripts = $('script');
                    // 获取全部script标签对象
                    _this.preg_adver(preg_length,scripts,preg);
                    var iframes = $('iframe');
                    //获取全部iframe标签对象
                    _this.preg_adver(preg_length,iframes,preg);
                }, 200);//为比较彻底清除异己资源，200ms遍历一遍，可自行调整

            }
        },
        getThreeTime:function(){
            var resultDate,year,month,date;
            var currDate = new Date();
            year = currDate.getFullYear();
            month = currDate.getMonth()+1;
            date = currDate.getDate();
            switch(month)
            {
                case 1:
                case 2:
                case 3:
                    month += 9;
                    year--;
                    break;
                default:
                    month -= 3;
                    break;
            }
            month = (month < 10) ? ('0' + month) : month;
            resultDate = year + '-'+month+'-'+date;
            var strTime = new Date(Date.parse(resultDate.replace(/-/g, "/")));
            strTime = strTime.getTime()/1000;
            return strTime;
        },
        isLoding:true,
        Ajax:function(url,data,c,type,dt,jp){
            var _this = this;
            data=$.extend({},data);
            var rtime=Math.round(new Date().getTime()/1000);
            var md5_sign=JSON.stringify(data)+'_'+_this.getItem('enKey')+'_'+rtime;
             md5_sign=md.md5(md5_sign)
            // console.log(data.mark)
            $.ajax({
                type:type||'GET',
                url:url,
                data:data,
                dataType:dt||'jsonp',
                jsonp: jp||"callback",
                headers:{
                    "X-CORS":1,//1:跨域（web端需要）
                     'X-SID':this.getItem('token')||0,
                    'X-DID':'192.16.1.166',//设备唯一标识
                    'X-RTIME':rtime,//请求时间戳
                     'X-SIGN':md5_sign,//'0',//签文
                    'X-UA': navigator.userAgent,
                     'X-AGENT':'0',//代理ID
                },
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                beforeSend:function(XMLHttpRequest){
                    if(_this.isLoding) {
                        var $loading = $('<div class="loading-read"><img src="/images/loading/01.gif" style="width: 0.5rem"/></div>')
                        $("body").append($loading);
                    }
                },
                success:function(res){
                    if(c)c(res);
                },
                complete:function(XMLHttpRequest,textStatus){
                    _this.isLoding=false
                    $(".loading-read").remove();
                },
                error:function(XMLHttpRequest, textStatus, errorThrown) {
                    $(".loading-read").remove();
                    $(".loaDings").remove();
                    _this.isLoding=true
                    _this.alert('请求失败',"error");
                },
            });
        },
        loadTime:0,
        clearTimeLoading:null,
        loadHtml:function (load) {
            var _this=this;
            _this.clearTimeLoading=load.is;
            if(!load.is){//开关
                $(".loaDings").remove();
                return
            }else {
                _this.loadTime=load.time;
                var $html=$('<div class="loaDings"><div class="loading_content"> <div class="loadImg"></div><p class="txtTime">'+load.txt+'(<span class="times">'+load.time+'</span>S)...</p> </div> </div>');
                $("body").append($html);
                _this.loadSetTime();
            }

        },
        loadSetTime:function () {
            var _this=this;
            setTimeout(function () {
                if(!_this.clearTimeLoading)return false
                $('.times').text(++_this.loadTime);
                if(_this.loadTime>15){
                    $(".loaDings").remove();
                    cn.alert('请求超时');
                    return false
                }
                _this.loadSetTime()
            },1000)
        },
        getQueryString:function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        },
        getHtmlDocName:function() {
            var str = window.location.href;
            str = str.substring(str.lastIndexOf("/") + 1);
            str = str.split("?")[0];
            str = str.substring(0, str.lastIndexOf("."));
            return str;
        },
        toFixed:function(d,x){
            return d.toFixed(x||2);
        },
        alert:function(msg,err){
            var $msgModel=$('<div class="modelMsg"><div class="msgTxt">'+msg+'</div></div>');
            $('body').append($msgModel)
            setTimeout(function () {
                $msgModel.remove()
            },2000)
        },
        dialog:function(option){

            var $model=$('<div class="model_over "></div>');
            var $content=$('<div class="model_content fade-enter-active"></div>');

            var $mHead=$('<div class="model_head">'+(option.head||"")+'</div>');
            var $mBody=$('<div class="model_body" style="padding:'+(option.head?'':'0.15rem')+'">'+(option.body||"")+'</div>');
            var $mFoot=$('<div class="model_foot"></div>');
            var btn='';
            if(option.cBack){
                btn+='<a href="javascript:;" class="truebtn">'+option.cBack.text+'</a>';
            }else{
                btn+='<a href="javascript:;" class="truebtn">'+(option.close||"确定")+'</a>';
            }
            if(option.confirm){
                btn+='<a href="javascript:;" class="zp-btn">'+option.confirm.text+'</a>';

            }
            $content.append($mHead);
            $content.append($mBody);
            $content.append($mFoot)
            $mFoot.append(btn)
            $('body').append($content);
            $('body').append($model);
            $('.truebtn').on('click',function(){
                if(option.cBack)option.cBack.callBack();
                $('.model_content').addClass('fade-leave-active').removeClass('fade-enter-active');
                setTimeout(function () {
                    $model.remove();
                    $content.remove();
                    $('.model_content').removeClass('fade-leave-active')
                },400)
               // $model.remove();
            });
            if(option.confirm){
                $('.zp-btn').on('click',function(){
                    option.confirm.callBack();
                    // if($('.model_content').hasClass()){
                    //
                    // }
                    $('.model_content').addClass('fade-leave-active').removeClass('fade-enter-active');
                    setTimeout(function () {
                        $model.remove();
                        $content.remove();
                        $('.model_content').removeClass('fade-leave-active')
                    },400)
                });
            }
        },
        modelDialog:function(option){
            var $dialog = $('<div class="zp-dialog fade-leave-active"></div>'),
                $inner = $('<div class="zp-dialog-inner"></div>'),
                $content = $('<div class="zp-content"></div>'),
                $btn=$('<div class="zp-btnbox"></div>'),
                btn='';
            $dialog.append($inner);
            $inner.append($content);
            if(option.xVal){
                btn+='<a href="javascript:;" class="truebtn">'+option.xVal[0].txt+'</a>';
            }else{
                btn+='<a href="javascript:;" class="truebtn">'+(option.btnValue||"确定")+'</a>';
            }
            if(option.btn){
                btn+='<a href="javascript:;" class="zp-btn">'+option.btn[0].txt+'</a>';

            }
            var con = $('<p>'+option.msg+'</p>').appendTo($content);
            $btn.append(btn);
            $inner.append($btn);
            if($('body .zp-dialog').length>0)return false
            $('body').append($dialog);

            $('.truebtn').on('click',function(){
                if(option.xVal)option.xVal[0].callBack();
                $dialog.remove();
            });
            if(option.btn){
                $('.zp-btn').on('click',function(){
                    option.btn[0].callBack();
                    $dialog.remove();
                });
            }
        },
    }
    Date.prototype.Format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
});